package com.xb.sourest.ui;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ocnyang.cartlayout.bean.CartItemBean;
import com.ocnyang.cartlayout.bean.ICartItem;
import com.ocnyang.cartlayout.listener.CartOnCheckChangeListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.unfind.myahmt.xyb.network.NetworkScheduler;
import com.xb.sourest.R;
import com.xb.sourest.adapter.CarAdapter;
import com.xb.sourest.adapter.ShopCarAdapter;
import com.xb.sourest.api.ApiClent;
import com.xb.sourest.api.ExceptionScheduler;
import com.xb.sourest.base.BaseLazyFragment;
import com.xb.sourest.base.MultiStateViewOpera;
import com.xb.sourest.bean.GoodsItem;
import com.xb.sourest.bean.ShopGoodsBean;
import com.xb.sourest.view.ItemLongClickMaskHelper;
import com.xb.sourest.view.MultiStateView;
import com.xb.sourest.view.ScrollCallbackRecyclerView;
import com.xd.navi.PhoneUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 购物车
 */
public  class CarFragment extends BaseLazyFragment implements ScrollCallbackRecyclerView.ScrollCallbackListener,ItemLongClickMaskHelper.ItemMaskClickListener{

    @BindView(R.id.multi_state_view)
    MultiStateView multiStateView;
    @BindView(R.id.goods_refresh_layout)
    SmartRefreshLayout mSmartFresh;
    @BindView(R.id.rcv_shop_car)
    ScrollCallbackRecyclerView rcv_shop_car;
    @BindView(R.id.checkbox_all)
    CheckBox checkbox_all;
    @BindView(R.id.tv_total_price)
    TextView tv_total_price;
    @BindView(R.id.btn_go_to_pay)
    Button btn_go_to_pay;

    private MultiStateViewOpera mOpera;

    private int totalCheckedCount;   //勾选的商品总数量，店铺条目不计算在内
    private int totalCount;        //购物车商品ChildItem的总数量，店铺条目不计算在内
    private double totalPrice;     //勾选的商品总价格
    private int selectTotalCount;   //所选的商品总数


    private CarAdapter mCarAdapter;
    private List<GoodsItem> goodsItemList = new ArrayList<>();
    private ItemLongClickMaskHelper mMaskHelper;
    private int onLongItemPosition;
    @Override
    protected void initData() {
      //传递过来操作
        mMaskHelper = new ItemLongClickMaskHelper(mActivity);
        mMaskHelper.setMaskItemListener(this);
    }

    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_car;
    }


    @Override
    public void onNetStateChange(boolean isConnect) {
        super.onNetStateChange(isConnect);
        if (isConnect){
            loadData();
        }
    }


    @Override
    protected void loadData() {
        mOpera = new MultiStateViewOpera(multiStateView, new MultiStateViewOpera.MultiStateCallBack() {
            @Override
            public void request() {
                loadData();
            }
        });
        //刷新操作
        mSmartFresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(2000);
                if (checkbox_all.isChecked()){
                    checkbox_all.setChecked(false);
                }
                loadData();
            }
        });

        goodsItemList.clear();

        rcv_shop_car.setLayoutManager(new LinearLayoutManager(mActivity));
        rcv_shop_car.setScrollCallbackListener(this);
        mCarAdapter = new CarAdapter(mActivity, goodsItemList);

        mCarAdapter.setOnCheckChangeListener(new CarAdapter.OnCheckChangeListener() {
            @Override
            public void onCaulueCallBack(List<GoodsItem> goodsItems) {
                calculate(goodsItems);
            }

            @Override
            public void onLongClick(List<GoodsItem> goodsItems,View view,int position) {
                onLongItemPosition = position;
                Log.e("fragment",position+"");
                //ToDo()长按
                if (mMaskHelper != null){
                    mMaskHelper.setRootFrameLayout((FrameLayout)view);
                }
            }

            @Override
            public void onItemClick() {
                if (mMaskHelper != null){
                    mMaskHelper.dismissMaskLayout();
                }
            }
        });
        rcv_shop_car.setAdapter(mCarAdapter);


        //ToDo()模拟购物车数据
        for (int i = 0; i < 5; i++) {
            GoodsItem goodsItem = new GoodsItem();
            goodsItem.setGoodsId(i+"");
            goodsItem.setGoodsName("商品"+i);
            goodsItem.setImage("");
            goodsItem.setNumber(i+1);
            goodsItem.setPrice(10.0+i+0.1);
            goodsItem.setId(i);
            goodsItemList.add(goodsItem);
        }
        mCarAdapter.notifyDataSetChanged();



        //TodO()网络请求
    }

    @Override
    protected void upView() {
        //TodO()绑定视图后的操作
        title.setText("购物车");
        top_back_btn.setVisibility(View.GONE);
        tv_total_price.setText("￥ 0.00");
    }



    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给相关的 textView 进行数据填充
     */
    private void calculate(List<GoodsItem> goodsItems) {
        totalCheckedCount = 0;
        selectTotalCount =0;
        totalCount = 0;
        totalPrice = 0.00;
        if (goodsItems !=null){
            if (goodsItems .isEmpty()){
                totalCheckedCount = 0;
            }else {
                for (GoodsItem goodsItem : goodsItems){
                    if (goodsItem.isChecked()){
                        totalCheckedCount++;
                        totalPrice += (goodsItem.getPrice() * goodsItem.getNumber());
                        selectTotalCount += goodsItem.getNumber();
                    }
                }
            }
        }
        btn_go_to_pay.setEnabled(totalCheckedCount != 0);
        tv_total_price.setText("￥" + PhoneUtils.fromatAmount(totalPrice));
        if (checkbox_all.isChecked() && (totalCheckedCount == 0 || totalCheckedCount  != goodsItems.size())) {
            checkbox_all.setEnabled(false);
        }
        if (totalCheckedCount != 0 && (!checkbox_all.isChecked()) && totalCheckedCount == goodsItems.size()) {
            checkbox_all.setChecked(true);
        }
    }

    @OnClick({R.id.checkbox_all})
    public  void onClick(View view){
        switch (view.getId()){
            case R.id.checkbox_all:
                if (mCarAdapter != null){
                    mCarAdapter.checkAll(((CheckBox) view).isChecked());
                }
                break;
        }
    }

    @Override
    public void scrollChanged() {
        if (mMaskHelper!= null){
            mMaskHelper.dismissMaskLayout();
        }
    }

    @Override
    public void deleteItem() {
        if (mCarAdapter!= null){
            mCarAdapter.delete(onLongItemPosition);
        }
    }
}
